// Copyright (c) 2011 The Kiwii Authors. All rights reserved.
// Use of this source code is governed by the New BSD License that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#ifndef KIWII_TCP_CONNECTION_INCLUDED
#define KIWII_TCP_CONNECTION_INCLUDED

#include "net/EventLoopBase.hxx"
#include <unistd.h>
#include <memory>
#include <functional>

namespace kiwii {
  namespace net {

    class TcpConnection {
    public:
      TcpConnection(int connfd, EventLoopBase& el);
      virtual ~TcpConnection();

      int fd() const { return connfd_; }

      //size == 0 indicates that client has closed the connection
      typedef std::function<size_t(char const* buffer, size_t size)> MessageHandler;

      //Set handler for processing received message
      void setMessageHandler(MessageHandler const& handler) {
	msgHandler_ = handler;
      }

      void send(char const* buf, std::size_t size);

    private:
      //Use object to manage resource to make code exception-safe
      struct FdWrapper {
	FdWrapper(int fd) : fd_(fd) {}
	~FdWrapper() { close(fd_); }
	operator int() const { return fd_; }
	int fd_;
      } connfd_;

      EventLoopBase& el_;

      static int const INIT_BUFFER_SIZE = 2048;

      std::unique_ptr<char[]> inputBuffer_;
      size_t inputBufferSize_;
      size_t inTo_; //Indicates where to write next char into the input buffer.

      std::unique_ptr<char[]> outputBuffer_;
      size_t outputBufferSize_;
      size_t outTo_;

      MessageHandler msgHandler_;
    };

  }
}

#endif
